<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\tool\Result;
use think\facade\View;
use think\response\Json;
use app\common\model\Coupon as CouponModel;
use app\common\model\UserCoupon;

class Coupon extends Base
{

    /**
     * get: 优惠券
     * path: info
     * method: info
     * param: type - 注册赠送1、购买赠送2
     */
    public function info()
    {
        $type = $this->request->param('type');
        $info = CouponModel::where(['type'=>$type,'is_del'=>0,'status'=>1])->find();
        $info->is_receive = $this->user->is_receive;
        return Result::success('获取成功',$info);
    }

    /**
     * post: 领取优惠券
     * path: receive
     * method: receive
     * param: id  优惠券id
     */
    public function receive()
    {
        $id = $this->request->param('id');
        $Coupon = CouponModel::find($id);
        $data['uid'] = $this->user->id;
        $data['coupon_id'] = $Coupon->id;
        $data['title'] = $Coupon->title;
        $data['sale_money'] = $Coupon->amount;
        $data['type'] = $Coupon->type;
        $data['update_time'] = time();
        if($id==1)
        {
            \app\common\model\User::update(['is_receive'=>1],['id'=>$this->user->id]);
        }
        $create = UserCoupon::create($data);
        if($create)
        {
            return Result::success('领取成功');
        }else{
            return Result::fail('领取失败');
        }
    }


    /**
     * get: 我的优惠券
     * path: getList
     * method: getList
     * param: page - page
     * param: status - status 0未使用 1已使用
     */
    public function getList(): \think\Response
    {
        $param = $this->request->param();
        $map = ['uid'=>$this->user->id,'status'=>$param['status'],'is_del' => 0];
        $list = UserCoupon::getPageList($map, 'id,title,sale_money,status', $param['page'], 20, false);
        if($list['code']>0)
        {
            return Result::success('获取成功',$list);
        }else{
            return Result::fail('获取失败');
        }
    }

}

